package com.llkj.qingnianguoxue.util;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 后台服务下载文件
 */
public class DownloadFilesService extends Service {
    private List<String> fileNameList = new ArrayList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null && intent.hasExtra("bookFile") && intent.hasExtra("bookName")){
            String fileUrl =intent.getStringExtra("bookFile");
            String fileName =intent.getStringExtra("bookName");
            fileNameList.add(fileUrl);
            downloadPdfFile(fileUrl,fileName);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 文件下载
     */
    private void downloadPdfFile(final String mPdfUrl, final String mFileName){
        final String dir = Utils.getAppBooksDir(getApplicationContext());
        final String fileName = mFileName+".pdf";
        File bookFile = new File(dir,fileName);
        if(bookFile!=null && bookFile.exists()){
            if(fileNameList.contains(mPdfUrl)){
                fileNameList.remove(mPdfUrl);
            }
            return;
        }
        //需要优化，判断是否下载过
        OkHttpUtils//
                .get()//
                .url(mPdfUrl)//
                .build()//
                .execute(new FileCallBack(dir, fileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        downloadPdfFile(mPdfUrl,fileName);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        if(response != null && response.exists() && fileNameList.contains(mPdfUrl)){
                            fileNameList.remove(mPdfUrl);
                        }
                    }
                });
    }
}
